//
//  JAComposeController.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/2.
//  Copyright © 2017年 Arvin. All rights reserved.
//

import UIKit
import SVProgressHUD

private let identifier = "identifier"

/// 允许添加的最大图片张数
private let maxPictureCount = 7

class JAComposeController: UIViewController {
    ///数据源数组
    var dataSourceArr: [UIImage] = []
    
    ///配图视图的collectionView
    lazy var pictureView: UICollectionView = {
        //设置layout
        let layout =  UICollectionViewFlowLayout()
        let cellWH = (screenWidh - 40)/3
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        //最小行间距和最小列间距
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        
        //创建collectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(JAComposeCell.self, forCellWithReuseIdentifier: identifier)
        
        return collectionView
    }()
    
    lazy var composeButton: UIButton = {
        
        //2.添加发布按钮
        let composeButton = UIButton(title: "发布", titleColor: UIColor.white, bgImage: "new_feature_finish_button", target: self, action: #selector(compose))
        
        //设置发布按钮的disable状态
        composeButton.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        
        composeButton.setTitleColor(UIColor.gray, for: .disabled)

        return composeButton
    }()
    
    ///创建底部的toolBar
    lazy var toolBar: UIToolbar = UIToolbar()
    
    ///文本输入框
    lazy var textView: JATextView = JATextView()
    
    /// 添加或删除图片时,选中的cell的index
    var selectedIndex: Int = 0
    
    /// 记录键盘类型: 0是系统键盘, 1是自定义键盘
    var keyboardType: Int = 0
    
    /// toolBar是否执行动画
    var isAnimatin: Bool = true
    
    ///自定义键盘
    lazy var customKeyboard: JACustomKeyboard = {
        let mykeyborad = JACustomKeyboard(frame: CGRect(x: 0, y: 0, width: screenWidh, height: 216))
        mykeyborad.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        return mykeyborad
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.automaticallyAdjustsScrollViewInsets = false
        setupUI()
        
        //监听键盘frame的变化
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
         NotificationCenter.default.addObserver(self, selector: #selector(insertOrDeleteEmotion(notification:)), name: emotionButtonClickedNotification, object: nil)
    }
}

// MARK: - 事件处理
extension JAComposeController {
    @objc fileprivate func insertOrDeleteEmotion(notification: Notification) {
        if let userInfo = notification.userInfo, let action = userInfo["action"]
            as? Bool {
            //删除操作
            if action == false {
                textView.deleteBackward()
            } else {
                if let emotion = userInfo["emotion"] as? JAEmotionModel {
                     textView.insertEmotion(emotion: emotion)
                }
            }
        }
    }
    ///返回
    @objc fileprivate func back() {
        
        dismiss(animated: true, completion: nil)
    }
    ///发布微博
    @objc fileprivate func compose() {
        
        //显示一个正在转动的菊花
        SVProgressHUD.show()
        let  status = (textView.text)!
        
        //默认值是nil
        var imageData: Data?
        
        if dataSourceArr.count > 0 {
            imageData = UIImagePNGRepresentation(dataSourceArr[0])
        }
        
        NetworkTool.shared.updateStatus(status: status, imageData: imageData) { (response) in
            SVProgressHUD.dismiss()
            
            //收起键盘
            self.textView.resignFirstResponder()
            
            //延迟一秒执行
            after(1) {
                self.dismiss(animated: true, completion: nil)
            }
        }
        
    }
    ///切换键盘
    @objc fileprivate func changeKeyBoard() {
        
        isAnimatin = false
        textView.resignFirstResponder() //收起键盘
        isAnimatin = true
        
        //是系统键盘,切成自定义键盘
        if keyboardType == 0 {
            textView.inputView = self.customKeyboard
            keyboardType = 1
        } else {
            textView.inputView = nil
            keyboardType = 0
        }
        
        textView.becomeFirstResponder() //弹出键盘
    }
    
    /// 当键盘将要发生变化时调用
    /// - Parameter notification: 通知
    @objc fileprivate func keyboardWillChange(notification: Notification) {
        if isAnimatin == true {
        if let userInfo = notification.userInfo,
            let rect = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
            let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as?
            TimeInterval {
            //键盘将要移动到的y坐标的值
            let endY = rect.cgRectValue.origin.y
            let offset = endY - screenHeight
            
            //调整toolBar的布局
            toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offset)
            })
            
            //强制更新UI的布局
            UIView.animate(withDuration: duration, animations: {
                self.view.layoutIfNeeded()
            })
        }
      }
    }
}

// MARK: - 设置UI
extension JAComposeController {
    fileprivate func setupUI () {
        
        self.view.backgroundColor = UIColor.white
        
        //设置导航条
        setupNavigationBar()
        
        //设置textView
        setupTextView()
        
        //设置toolBar
        setupToolBar()
        
        //设置配图视图
        setupPictureView()
    }
    
    ///设置配图视图
    func setupPictureView() {
        pictureView.backgroundColor = UIColor.yellow
        textView.addSubview(pictureView)
        pictureView.snp.makeConstraints { (make) in
            make.left.equalTo(textView).offset(10)
            make.top.equalTo(textView).offset(100)
            make.size.equalTo(CGSize(width: screenWidh-20, height: screenWidh-20))
        }
        
    }
    
    ///设置导航条
    func setupNavigationBar () {
        
        //1.添加返回按钮
        let  cancelButton = UIButton(title: "取消", titleColor: UIColor.white,  bgImage: "new_feature_finish_button", target: self, action: #selector(back))
        cancelButton.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
        let left = UIBarButtonItem(customView: cancelButton)
        navigationItem.leftBarButtonItem = left
        
        //2.添加发布按钮
        composeButton.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
        let right = UIBarButtonItem(customView: composeButton)
        navigationItem.rightBarButtonItem = right

        //设置button是否可以点击必须在将button添加到父视图上之后, 才可以生效
        composeButton.isEnabled = false
        
        //3.设置title
        let titleLabel = UILabel(title: nil, alignment: .center)
        //创建一个可变的富文本("发布微博")
        let titleText = NSMutableAttributedString(string: "发布微博\n", attributes: [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16)])
        
        //创建一个不可变的富文本("用户名")
        let userText = NSAttributedString(string: "\((JAUserAccount.shared.screen_name)!)", attributes: [NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12)])
        
        titleText.append(userText)
        titleLabel.attributedText = titleText
        titleLabel.sizeToFit()
        navigationItem.titleView = titleLabel
    }
    
    //设置textView
    func setupTextView () {
        
        textView.placeHoder = "请输入微博内容..."
        self.view.addSubview(textView)
        textView.delegate = self
        
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(0)
        }
        
    }
    
    //设置toolBar
    func setupToolBar() {
        
        //创建一个toolBar
        self.view.addSubview(toolBar)
        
        //设置toolBar背景图片
        toolBar.setShadowImage(UIImage.pureImage(color: UIColor(white: 0.9, alpha: 0.9)), forToolbarPosition: .any)
        toolBar.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forToolbarPosition: .any, barMetrics: .default)
        
        //toolBar自动布局
        toolBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
        }
        
        //创建toolBar的items的参数字典字数组
        let dicArray: [[String: Any]] = [["image":"compose_mentionbutton_background", "selector": #selector(changeKeyBoard)],["image":"compose_trendbutton_background", "selector": #selector(changeKeyBoard)],["image":"compose_camerabutton_background", "selector": #selector(changeKeyBoard)], ["image":"compose_emoticonbutton_background", "selector": #selector(changeKeyBoard)], ["image":"compose_keyboardbutton_background", "selector": #selector(changeKeyBoard)]]
        
        var items: [UIBarButtonItem] = []
        
        //遍历字典数组创建buttonitems
        for dic in dicArray {
            let button = UIButton(title: nil, image: dic["image"] as? String, target: self, action: dic["selector"] as? Selector)
            let buttonItem = UIBarButtonItem(customView: button)
            button.sizeToFit()
            let flexButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            
            items.append(buttonItem)
            items.append(flexButtonItem)
        }
        
        items.removeLast()
        
        //设置items
        toolBar.items = items
    }
    
}

extension JAComposeController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //选择照片结束时会调用
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取原图
        let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        originalImage.resizeImage(size: CGSize(width: 100, height: 100)) { (image)
            in
        //判断是添加还是替换, 如果是加号的cell, 说明是添加, 否则说明是替换
        //加号按钮, 添加
        if self.selectedIndex == self.dataSourceArr.count {
            self.dataSourceArr.append(image!)
        } else {
            self.dataSourceArr[self.selectedIndex] = image!
        }
        
        //刷新
        self.pictureView.reloadData()
        
        //将pickerViewController dismiss掉
        self.dismiss(animated: true, completion: nil)
    }
  }
}


// MARK: - 实现collectionView的数据源和代理
extension JAComposeController: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return dataSourceArr.count == maxPictureCount ? maxPictureCount : dataSourceArr.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! JAComposeCell
        
        cell.backgroundColor = UIColor.randomColor()
        
        cell.delegate = self
        
        //如果没有达到最大图片张数,并且是最后一个cell, 那么显示是加号按钮, cell的image设为nil
        if indexPath.item == dataSourceArr.count {
            cell.image = nil
        } else {
            cell.image = dataSourceArr[indexPath.item]
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        print("hello, world")
    }
}

/// MARK: - 实现textView的代理
extension JAComposeController: UITextViewDelegate {
    // 文字发生变化时调用
    // - Parameter textView: textView
    func textViewDidChange(_ textView: UITextView) {
        composeButton.isEnabled = textView.text.characters.count > 0
    }

}

//MARK: - 实现代理方法
extension JAComposeController: JAComposeCellDelegate {
    ///添加或删除图片
    /// - Parameter cell: 当前被点击的cell
    func addOrReplaceImage(cell: JAComposeCell) {
        //获取被点击的cell的index
        selectedIndex = (pictureView.indexPath(for: cell)?.item)!
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        present(imagePicker, animated: true, completion: nil)
        
    }
    
    func deleteImage(cell: JAComposeCell) {
        
        let index = (pictureView.indexPath(for: cell)?.item)!
        dataSourceArr.remove(at: index)
        //刷新
        pictureView.reloadData()
    }
}

